import { session } from "@ui/utils/temp";
import { getMenuList, getSystemList, MAGIC_SUCC_CODE } from "@ui/vue/api";
import { xtlj } from "@ui/vue/router";
export const menu = ref<UserMenu[]>(session('user-menu') || []),
  menuList = ref<UserMenu[]>([])
let promise: any
export function getMenu() {
  if (!menu.value.length) {
    if (!promise)
      promise = getSystemList({ id: '123' }).then(({ code, data }) => {
        if (code == MAGIC_SUCC_CODE) {
          return Promise.all(data.map((sys) => {
            sys.pageName = sys.sysName
            sys.pageId = sys.sysId
            return getMenuList({ xtid: sys.sysId }).then(({ data = [] }) => {
              data.forEach(group => {
                group.pageName = group.groupName
                group.pageId = group.groupId
              })
              sys.page = data
            })
          })).then(() => {
            menu.value = data
            session('user-menu', data)
          })
        }
      })
  } else {
    promise = Promise.resolve()
  }
  return promise.then(() => {
    const arr: UserMenu[] = [], data: UserMenu[] = menu.value
    data.forEach(({ page: groups = [] }) => {
      groups.forEach(({ page: pages = [] }) => {
        pages.forEach(page => {
          let path: string[] = []
          if (/^http/.test(page.pageUrl)) {
            path = ['iframe', page.pageId]
            page.params = { xtm: 'iframe' }
          } else {
            const params: Record<typeof xtlj[number], string> = {}
              , len = xtlj.length
            path = page.pageUrl.split('/').filter(it => it)
            path.forEach((it, i) => {
              if (i < len) {
                params[xtlj[i]] = it;
              }
            })
            page.params = params
            page.pageUrl = path.join('/')
          }
          page.path = path.join('/')
          arr.push(page)
        })
      })
    })
    menuList.value = arr
  })
}